package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.CaseCategoryChangeFormDto;
import cn.livingCloud.dto.CaseCategoryDto;
import cn.livingCloud.entity.core.CaseCategory;
import cn.livingCloud.repository.CaseCategoryMapper;
import cn.livingCloud.repository.CaseMapper;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created by 唐旭 on 2016/6/26.
 */
public class CaseCategoryChangeFormDtoLoader {
    private transient CaseMapper mapper = BeanProvider.getBean(CaseMapper.class);
    private transient CaseCategoryMapper caseCategoryMapper = BeanProvider.getBean(CaseCategoryMapper.class);
    private String uuid;

    public CaseCategoryChangeFormDtoLoader(String uuid) {
        this.uuid = uuid;
    }

    public CaseCategoryChangeFormDto load() {
        CaseCategoryChangeFormDto formDto = new CaseCategoryChangeFormDto(uuid);
        formDto.setCategoryUuid(mapper.selectByPrimaryKey(uuid).getCaseCategoryUuid());
        List<CaseCategory> all = caseCategoryMapper.getAll();
        List<CaseCategoryDto> list = formDto.getList();
        for (CaseCategory category : all) {
            if (StringUtils.isEmpty(category.getParentUuid())) {
                list.add(new CaseCategoryDto(category));
            }
        }
        addSubCategory(list, all);
        return formDto;
    }

    private void addSubCategory(List<CaseCategoryDto> categoryList, List<CaseCategory> all) {
        for (CaseCategoryDto caseCategoryDto : categoryList) {
            List<CaseCategoryDto> subList = caseCategoryDto.getSubList();
            for (CaseCategory category : all) {
                if (caseCategoryDto.getUuid().equals(category.getParentUuid())) {
                    subList.add(new CaseCategoryDto(category));
                }
            }
            addSubCategory(subList, all);
        }
    }
}
